package com.gae101;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gae101.service.ImageService;
import com.gae101.service.ImageServiceImpl;
import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

public class GetImageServlet extends HttpServlet{
	private static final long serialVersionUID = 1609474488319270790L;
	private static final Logger log = Logger.getLogger(GetImageServlet.class.getName());
	
	ImageService imageService = new ImageServiceImpl();
		
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {		
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		String loginUrl = userService.createLoginURL(req.getRequestURI());
		req.setAttribute("loginUrl", loginUrl);
		
		if (user == null) {
			resp.sendRedirect(loginUrl);
			return;
		}
		
		req.setAttribute("nickname", user.getNickname());
		req.setAttribute("logoutUrl", userService.createLogoutURL(req.getRequestURI()));
		
		String userId = user.getUserId();
		String imageId = req.getParameter("id");
		
		if (imageId == null) {
			List<Entity> images = imageService.findAll(userId);
			if (images.size() > 0) {
				req.setAttribute("last", images.get(0).getKey().getId());
			} else {
				req.setAttribute("last", 0);
			}
			req.setAttribute("images", images);
			req.getRequestDispatcher("images.jsp").forward(req, resp);
		} else {
			if (imageId.equals("last")) {
				resp.setContentType("application/json");
				Entity last = imageService.last(userId);
				JSONObject json = new JSONObject();
				if (last != null) {
					try {
						json.append("id", last.getKey().getId());
						json.append("date", last.getProperty("date"));
					} catch (JSONException e) {
						throw new RuntimeException(e);
					}
				}
				resp.getOutputStream().write(json.toString().getBytes());
			}
			else {
				resp.setContentType("image/jpeg");
				Entity image = imageService.get(Long.parseLong(imageId));
				if (image != null) {
					Blob imageBlob = (Blob) image.getProperty("image");
					resp.getOutputStream().write(imageBlob.getBytes());
				}
				else {
					log.warning("NOT exist");
				}
			}
		}
		
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
	}
	
	@Override
	public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String idStr = (String) req.getParameter("id");
		
		User user = UserServiceFactory.getUserService().getCurrentUser();
		String userId = user.getUserId();
		
		if (idStr != null) {
			Long id = Long.parseLong(idStr);
			imageService.delete(id);
		}
		
	}
}
